<template>
    <div id="order" class="new-order">
        <h1 class="page-title">
            新建订单
        </h1>

        <el-form class="page-content" :label-position="'left'" ref="order" :model="order" :rules="rules2" label-width="140px">
            <el-form-item label="客户姓名" prop="name">
                <el-input v-model="order.name" placeholder="请输入客户姓名"></el-input>
            </el-form-item>
            <el-form-item label="联系方式" prop="tel">
                <el-input v-model="order.tel" placeholder="请输入联系电话"></el-input>
            </el-form-item>
            <el-form-item label="品牌" prop="company_id">
                <el-select v-model="order.company_id" placeholder="请选择家装品牌">
                    <el-option v-for="co in companies" :key="co.id" :label="co.name" :value="co.id"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="材质" prop="material_id">
                <el-select v-model="order.material_id" @change="materialChange" placeholder="请选择家装材质">
                    <el-option v-for="ma in material" :key="ma.id" :label="ma.name" :value="ma.id"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="预估面积（㎡）" prop="square">
                <el-input v-model.number="order.square" @change="calTotal" placeholder="请输入预估面积"></el-input>
            </el-form-item>
            <el-form-item label="省市区" prop="address">
                <el-cascader :options="china" change-on-select v-model="order.address" :props="props">
                </el-cascader>
            </el-form-item>
            <el-form-item label="详细地址" prop="street">
                <el-input v-model="order.street" placeholder="请输入详细地址"></el-input>
            </el-form-item>
            <el-form-item label="预估价格（元）">
                <el-input v-model="order.total" :disabled="true"></el-input>
            </el-form-item>
            <el-form-item label="是否为安装单">
                <el-switch on-text="是" off-text="否" v-model="order.mount_order"></el-switch>
            </el-form-item>
            <template v-if="order.mount_order">
                <el-form-item label="安装时间" prop="datetime">
                    <el-date-picker type="datetime" placeholder="选择安装时间" v-model="order.datetime" :picker-options="setDate"></el-date-picker>
                </el-form-item>
                <el-form-item label="安装师傅">
                    <el-select v-model="server_id" clearable filterable remote placeholder="请选择安装师傅" :loading="loading" :remote-method="fetchMaster">
                        <el-option v-for="item in masters" :key="item.id" :label="item.real_name" :value="item.id"></el-option>
                    </el-select>
                </el-form-item>
            </template>
            <template v-else>
                <el-form-item label="测量时间" prop="datetime">
                    <el-date-picker type="datetime" placeholder="选择测量时间" v-model="order.datetime" :picker-options="setDate"></el-date-picker>
                </el-form-item>
                <el-form-item label="测量师傅">
                    <el-select v-model="server_id" clearable filterable remote :loading="loading" placeholder="请选择测量师傅" :remote-method="fetchMaster">
                        <el-option v-for="item in masters" :key="item.id" :label="item.real_name" :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
            </template>
            <el-form-item label="备注">
                <el-input type="textarea" placeholder="选填" v-model="order.remark"></el-input>
            </el-form-item>
            <el-form-item class="footer-item">
                <el-button type="primary" @click="createOrder('order')">立即创建</el-button>
                <el-button>取消</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>
<script>
import china from '../../utils/china'
import '../../styles/report/index.scss'

import { mapGetters, mapActions } from 'vuex'
export default {
    data() {
        // var checkTel = (rule, value, callback) => {
        //     if (value == null || !value) {
        //         return callback(new Error("客户电话不能为空"));
        //     }
        //     if (!Number.isInteger(value)) {
        //         return callback(new Error("必须为数字"))
        //     }
        // };
        var date = new Date();
        date = new Date(date.setDate(date.getDate() + 1))

        return {
            china: china,
            props: {
                value: 'name',
                label: 'name',
                children: 'childs'
            },
            itemWidth: 360,
            order: {
                name: null,
                tel: null,
                company_id: null,
                material_id: null,
                material: null,
                square: null,
                province: null,
                city: null,
                area: null,
                street: null,
                booking_date: null,
                install_date: null,
                facilitator_id: null,
                customer_service_id: null,
                mount_order: false,
                remark: null,
                customer_id: null,
                total: 0,
                address: [],
                datetime: date,

            },
            companies: [],
            material: [],
            // address: [],
            loading: false,
            masters: [],
            server_id: null,
            // datetime: date,
            setDate: {
                disabledDate(time) {
                    return time.getTime() < Date.now() - 8.64e7
                }
            },
            rules2: {
                tel: [{ type: 'string', required: true, pattern: /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/, message: '请输入正确的手机号码！', trigger: 'blur' }],
                name: [
                    { type: 'string', required: true, message: '请输入正确的客户姓名！', trigger: 'blur' }
                ],
                company_id: [
                    {
                        type: 'number', required: true, message: '请选择品牌！', trigger: 'blur'
                    }
                ],
                material_id: [
                    {
                        type: 'number', required: true, message: '请选择材质！', trigger: 'blur'
                    }
                ],
                square: [
                    { required: true, pattern: /^\d+(\.\d+)?$/, message: '请输入正确的预估面积！', trigger: 'blur' }
                ],
                address: [
                    {
                        type: 'array', required: true, trigger: 'blur', message: '请选择正确的省市区！'
                    }
                ],
                street: [
                    {
                        type: 'string', required: true, message: '请输入正确的详细地址', trigger: 'blur'
                    }
                ],
                datetime: [
                    {
                        type: 'object', required: true, message: '请输入正确的时间', trigger: 'blur'
                    }
                ]
            }
        };
    },

    computed: {
        ...mapGetters(['current_user'])
    },
    mounted() {
        this.fetchTemp()
    },
    watch: {
        'order.datetime': function(val, oldVal) {
            console.log(typeof(val), typeof(oldVal))
        },
        'order.company_id': function(val, oldVal) {
            // console.log(val, oldVal)
        },
        address(val, oldVal) {
            console.log(val, oldVal)
        }
    },
    methods: {
        calTotal() {
            let args = {
                company_id: this.order.company_id,
                material_id: this.order.material_id,
                material: this.order.material,
                square: this.order.square
            }
            if (this.order.material && this.order.square > 0) {
                this.$http.post("orders/cal_price", { material: this.order.material, square: this.order.square }).then(res => {
                    this.order.total = res.price
                })
            } else {
                this.$message({
                    type: "error",
                    message: "不能计算价格, 无效的参数"
                })
                return false
            }
        },
        //创建订单
        createOrder(formName) {
            this.order.customer_id = this.current_user.id

            if (this.order.mount_order) {
                this.order.facilitator_id = this.server_id
                this.order.install_date = (Date.parse(new Date(this.datetime))) / 1000
            } else {
                this.order.customer_service_id = this.server_id
                this.order.booking_date = (Date.parse(new Date(this.order.datetime))) / 1000
            }

            [this.order.province, this.order.city, this.order.area] = this.order.address

            this.$refs[formName].validate((valid) => {
                if (valid) {
                    this.$http.post("orders/appoint", this.order).then(res => {
                        if (res.code == 200) {
                            this.$router.push({ name: "orders" })
                        }
                    })
                } else {
                    return false
                }
            })
        },
        fetchTemp() {
            let self = this
            self.$http.get("fetch_source").then(res => {
                self.companies = res.company
                self.material = res.material
            })
        },
        fetchMaster(q) {
            if (q !== '') {
                this.loading = true
                setTimeout(() => {
                    this.loading = false
                    this.$http.get("users/fetch_master", { params: { keyword: q } }).then(res => {
                        this.masters = res.users
                    })
                }, 2000)
            }
        },
        materialChange(val) {
            let m = this.material.filter(item => {
                return item.id == val
            })
            this.order.material = m[0].name
        },
    }
}
</script>

